<template>
  <div>
    <el-card class="card" style="max-width: 75vw">
      <div class="card-header">
        <el-text class="mx-1">当前社团：</el-text>
        <el-select v-model="clubSelect" @change="onClubChange" placeholder="--请选择--" style="width: 180px">
          <el-option v-for="item in clubList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <div class="searchPerson">
          <el-input v-model="inputName" style="width: 150px" placeholder="输入姓名" />
          <el-button type="primary" id="searchButton" @click="handleUpdateList">
            搜索
          </el-button>
        </div>

      </div>
      <div class="listTable">
        <el-table class="listTable" :data="membersListData" :border=true style="width: 100%" :max-height="'70vh'">
          <el-table-column prop="id" label="用户ID" :width="tableWidth[0]" :align="'center'" />
          <el-table-column prop="userName" label="姓名" :width="tableWidth[1]" :align="'center'" />
          <el-table-column prop="account" label="账号" :width="tableWidth[2]" :align="'center'" />
          <el-table-column prop="phoneNum" label="联系方式" :width="tableWidth[3]" :align="'center'" />
          <el-table-column prop="operation" label="操作" :width="tableWidth[4]" :align="'center'">
            <template #default="scope">
              <el-button  v-if="permission == 1 || permission == 0" id="buttonInDetails" @click="handleInDetails(scope.row)">加入社团详情</el-button>
              <el-button id="buttonNoticeShow" @click="handleShowInfo(scope.row)">信息详情</el-button>
              <el-button v-if="permission == 1 || permission == 0" type="primary" id="buttonReset" @click="handlePassword(scope.row)">重置密码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footerpager">
        <el-select v-model="pageSize" @change="onOptionChange"  placeholder="Select" style="width: 120px">
          <el-option v-for="size in pageSizeOptions" :key="size.value" :label="size.label" :value="size.value" />
        </el-select>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :pager-count="7"
          @current-change="handleUpdateList" layout="prev, pager, next" :total="totalNum" />
        <div class="pageNow">
          当前
          <input class="pageInput" @blur="onChangePage" v-model="setCurrentPage" />
          页，共
          {{ totalPage }}
          页
        </div>
      </div>
    </el-card>
  </div>

  <el-dialog v-model="dialogPassword" title="确认重置该账号的密码？" width="500" align-center>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogPassword = false">取消</el-button>
        <el-button type="primary" @click="resetPassword">
          重置为初始密码
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogFirst" title="加入的社团信息如下" width="700" align-center>
    <el-table :data="joinedClubList" style="width: 100%">
    <el-table-column prop="clubName" label="社团名称" width="180" />
    <el-table-column prop="clubLevel" label="级别" width="180" />
    <el-table-column prop="clubState" label="社团状态" />
  </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFirst = false">关闭详情</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogThird" title="详细个人信息" width="600" align-center>
    <div>
   <div class="infoFormitem">头像 
     <span class="avtor"> 
      <el-avatar :src="selfInfo.headImage" />
    </span>
    </div>
   <div class="infoFormitem">账号: &nbsp; {{ selfInfo.account }}</div>
   <div class="infoFormitem">姓名：&nbsp; {{ selfInfo.userName }}</div>
   <div class="infoFormitem">性别: &nbsp;{{ selfInfo.sex }}</div>
   <div class="infoFormitem">邮箱: &nbsp;{{ selfInfo.email }}</div>
   <div class="infoFormitem">电话: &nbsp;{{ selfInfo.phoneNum }}</div>
   <div class="infoFormitem">大学: &nbsp;{{ selfInfo.schName }}</div>
  </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogThird = false">关闭详情</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import api from '@/api';
import showMessageTip from '@/utils/showMessage';
import userStore from '@/stores/store';
import debounce from '@/utils/debounce';

const dialogPassword = ref(false);
const inputName = ref('');
const tableWidth = ref([]);
const tableWidthRatio = ref([0.15, 0.14, 0.18, 0.17, 0.36]);
const membersListData = ref([{
}]);
const clubSelect=ref();
const pageSize = ref(10);
const currentPage = ref(1);
const totalNum = ref(0);
const totalPage = ref(1); //总页数
const pageSizeOptions = ref([
  { value: 5, label: '5条/页' },
  { value: 10, label: '10条/页' },
  { value: 15, label: '15条/页' },
  { value: 20, label: '20条/页' },
])
const setCurrentPage = ref();
const clubList = ref([]);
const dialogFirst = ref(false);
const dialogThird = ref(false);
const permission = ref(userStore().getPermission); 
const selfInfo = ref({});
const newPersonId =ref();
const joinedClubList = ref([]);
var debounceSetColumnSize = null;

onMounted(() => {
  const width = document.querySelector('.card').getBoundingClientRect().width - 40;
  tableWidth.value[4] = width;
  for (let i = 0; i < 4; i++) {
    tableWidth.value[i] = tableWidthRatio.value[i] * width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
});
onMounted( () => {
  debounceSetColumnSize = debounce(setColumnSize, 300);
  window.addEventListener('resize', debounceSetColumnSize);
})
onUnmounted(() => {
  window.removeEventListener('resize', debounceSetColumnSize);
  debounceSetColumnSize.cancel();
});
const setColumnSize = () => {
  const width = document.querySelector('.card').getBoundingClientRect().width-40;
  tableWidth.value[4]=width;
  for(let i = 0; i<4 ;i++){
    tableWidth.value[i] = tableWidthRatio.value[i]*width;
    tableWidth.value[4] -= tableWidth.value[i];
  }
}

const onOptionChange = async () => {
  setCurrentPage.value = 1;
  currentPage.value = 1;
}
const onClubChange =async()=>{
  await handleUpdateList();
}
const onChangePage = async () => {
  if(Number(setCurrentPage.value) > totalPage.value){
    setCurrentPage.value = totalPage.value;
    currentPage.value = totalPage.value;
  }
  else if(setCurrentPage.value <=0 ){
    setCurrentPage.value = 1;
    currentPage.value = 1;
  }
  else{
    currentPage.value = Number(setCurrentPage.value);
  }
  await handleUpdateList();
}


const handleInDetails = async(rowData) => {
  const id = ref({personId:rowData.id})
  const result = await api.getPeopleJoinedClub(id.value)
  if(result[0]==0){
    const data = result[1].data;
    if(data.code==1){
      joinedClubList.value =data.data;
      for(let i=0;i<joinedClubList.value.length;i++){
         if(joinedClubList.value[i].clubLevel==0){
          joinedClubList.value[i].clubLevel='院级';
         }
         else joinedClubList.value[i].clubLevel='校级';
         if(joinedClubList.value[i].clubState==0){
          joinedClubList.value[i].clubState='可加入'
         }
         else{
          if(joinedClubList.value[i].clubState==1)
          joinedClubList.value[i].clubState='不可加入'
        else joinedClubList.value[i].clubState='停用'
         }
      }
    }
  }
  else{
    showMessageTip('网络请求失败','error')
  }
  dialogFirst.value = true;
  
}
const handlePassword = (rowdata) =>{ //重置密码按钮
  newPersonId.value=rowdata.id
  dialogPassword.value = true;

}

//处理显示用户信息
const handleShowInfo= async(rowData)=>{
  const id = ref({
    personId:rowData.id
  });
  const result = await api.getPelpleInfo(id.value);
  if(result[0]==0){
      const data =result[1].data.data;
      selfInfo.value =data;

      if(selfInfo.value.sex==1){
        selfInfo.value.sex='男';
      }
      else{
        selfInfo.value.sex='女';
      }
      if(selfInfo.value.email==null){
        selfInfo.value.email='暂无';
      }
      if(selfInfo.value.phoneNum==null){
        selfInfo.value.phoneNum='暂无';
      }
  }
  else{
    showMessageTip('网络请求失败','error')
  }
  dialogThird.value = true;
}

const resetPassword =async () => {
const id = ref({ personId: newPersonId.value})                                 
const result = await api.resetPassword(id.value);
if(result[0]==0){
  const data =result[1].data;
    if(data.msg=='success'){
      showMessageTip('已重置该用户密码','success');
      dialogPassword.value = false;
    }
    else{
      showMessageTip('操作失败','warning');
    }
}
else{
  showMessageTip('网络请求失败','error');
}

}

const getClubList = async () => {
  let reqRequest = null;
  if(permission.value == 1 || permission.value == 0){
    clubList.value = [];
    clubList.value.push({
      label: '全部',
      value: 0
    })
    const tmpClubId = userStore().getClubId;
    if(tmpClubId == -1){
      clubSelect.value = 0;
      return;
    }
    reqRequest = await api.getBasicClubInfo({ clubId: tmpClubId })
    if (reqRequest[0] == 0) {
      const data = reqRequest[1].data;
      if (data.code == 1) {
        if(data.data == null) return;
        clubList.value.push({
          label: data.data.clubName,
          value: tmpClubId
        })
        clubSelect.value = tmpClubId;
      }
      else {
        clubSelect.value = 0;
        showMessageTip('社团信息加载失败', 'error');
        return;
      }
    }
    else{
      showMessageTip('网络请求失败', 'error');
      return;
    }
  }
  else if(permission.value == 2){
    reqRequest = await api.getManagedClub();
    clubList.value = [];
    if (reqRequest[0] == 0) {
      const data = reqRequest[1].data;
      if (data.code == 1) {
        clubList.value = [];
        const tempClubList = data.data;
        for (let i = 0; i < tempClubList.length; i++) {
          const tempNameId = ref({
            label: tempClubList[i].clubName,
            value: tempClubList[i].clubId
          })
          clubList.value.push(tempNameId.value);
        }
        const tempClubId = userStore().getClubId;
        if(tempClubId == -1 ){
          clubSelect.value = tempClubList[0].clubId;
        }
        else{
          clubSelect.value = tempClubId;
        }
      }
      else {
        showMessageTip('社团信息加载失败', 'error');
        return;
      }
    }
    else{
      showMessageTip('网络请求失败', 'error');
      return;
    }
  }
}
const handleUpdateList = async () => {  
  const reqData = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
  if(clubSelect.value == null){
    return;
  }
  if(clubSelect.value != 0){
    reqData.clubId = clubSelect.value;
  }
  if(inputName.value != ''){
    reqData.userName = inputName.value;
  }
  const reqRequest = await api.getMemberList(permission.value,reqData);
  if(reqRequest == null){
    showMessageTip('数据错误ERROR', 'error');
    return;
  }
  if(reqRequest[0] == 0) {
    const data = reqRequest[1].data;
    if (data.code == 1) {
      totalNum.value = data.data.total;
      membersListData.value = [];
      membersListData.value = data.data.rows;
      totalPage.value = Math.ceil(data.data.total/pageSize.value);
    }
    else{
      showMessageTip('数据获取失败', 'error');
      return;
    }
  }
  else{
    showMessageTip('网络请求失败', 'error');
    return;
  }
  setCurrentPage.value = currentPage.value;
}

onMounted( async () => {
  await getClubList();
  await handleUpdateList();
})

watch(pageSize, async (newQuestion, oldQuestion) =>{
  await handleUpdateList();
})
</script>

<style scoped>
.listTable {
  margin-top: 12px;
}

:deep(.listTable .el-table__header-wrapper th) {
  background-color: #549DFD;
  color: #fff;
  font-family: 'Microsoft YaHei';
}

.footerpager{
  margin-top: 20px;
  padding-left: 5px;
  display: flex;
}
.pageNow{
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14.5px;
}
.pageInput{
  margin-left: 5px;
  margin-right: 5px;
  width: 25px;
  text-align: center;
}
.card-header{
  display: flex;
  padding-left: 5px;
}
.searchPerson{
  margin-left: 28px;
}
#searchButton{
  margin-left: 5px;
}
.infoFormitem{
line-height: 20px;
margin-top: 4%;
}
.avtor{
  position: relative;
  left:10%;
  margin-bottom: 10px;
  size: 'large';
}
</style>